<?php

include("sharepoint.class.php");
include("sharepointdata.class.php");

class BAL
{
    public $service;
    public $params;
    private $login_host;
    private $host;
    private $uid;
    private $pwd;
    private $contacts_list;

    private $totalRecords;

    function  __construct()
    {
        $this->service = new Sharepoint();

        $this->loadProperties();
    }

    public function getContacts($query_string)
    {
        $this->params = $this->getQueryStringValues($query_string);

        $credentials = $this->uid . ":" . $this->pwd;

        $contacts = $this->service->GetListData($this->contacts_list, $credentials);

        $results = array();

        foreach($contacts->entry as $contact)
        {
            $c = new ContactsData();

            $c->id = $contact->id;
            $c->title = $contact->title;

            $properties = $contact->content->children("http://schemas.microsoft.com/ado/2007/08/dataservices/metadata")->properties->children("http://schemas.microsoft.com/ado/2007/08/dataservices");

            $c->firstName = $properties->FirstName;
            $c->lastName = $properties->LastName;
            $c->email = $properties->Email;
            $c->phone = $properties->Phone;

            $results[] = $c;
        }

        if(is_array($results))
        {
            $this->totalRecords = count($results);
        }
        
        if(isset ($this->params["startRow"]) && isset ($this->params["numberOfRows"]))
        {
            $results = $this->getPagedData($results, $this->params["startRow"][0], $this->params["numberOfRows"][0]);
        }

        return $results;
    }

    public function getPagedData($data, $startRow, $numOfRows)
    {
        if(is_array($data) && count($data) > 0)
        {
            if(count($data) > $startRow)
            {
                $startIndex = $startRow > 1 ? $startRow - 1 : 0;

                $endIndex = $startIndex + $numOfRows;

                if($endIndex > count($data))
                {
                    $endIndex = count($data);
                }

                $result_array = array();

                for($i = $startIndex; $i < $endIndex; $i++)
                {
                    $result_array[] = $data[$i];
                }

                return $result_array;
            }
        }

        return $data;
    }

    public function getSearchResults($queryString)
    {
        $keyword = $this->getSearchKeyword($queryString);

        $results_array = array();

        $query = str_replace("*", "", $keyword);

        $records = $this->service->PillSearch(urlencode($query));

        if($records["record_count"])
        {
            $this->totalRecords = $records["record_count"];
        }

        if($records)
        {
            foreach($records->pill as $pill_data)
            {
                $record = new PillBoxData();

                $record->productCode = $pill_data->PRODUCT_CODE;
                $record->colorCode = $pill_data->SPLCOLOR;
                $record->shapeCode = $pill_data->SPLSHAPE;
                $record->size = $pill_data->SPLSIZE;
                $record->dosageInfo = $pill_data->RXSTRING;
                $record->ingredients = $pill_data->INGREDIENTS;

                $results_array[] = $record;
            }
        }

        return $results_array;
    }

    public function getTotalRecords()
    {
        return $this->totalRecords;
    }

    public function getSearchKeyword($queryString)
    {
        $searchKeyword = "";

        $this->params = $this->getQueryStringValues($queryString);

        if($this->params)
        {
            if(isset ($this->params["searchValue"]))
            {
                if(is_array($this->params["searchValue"]) && count($this->params["searchValue"]) > 0)
                {
                    $searchKeyword = $this->params["searchValue"][0];
                }
                else
                {
                    $searchKeyword = $this->params["searchValue"];
                }
            }
        }

        return $searchKeyword;
    }

    public function getSearchCount()
    {
        $searchCount = 10;

        if($this->params)
        {
            if(isset ($this->params["numberOfRows"]))
            {
                if(is_array($this->params["numberOfRows"]) && count($this->params["numberOfRows"]) > 0)
                {
                    $searchCount = $this->params["numberOfRows"][0];
                }
                else
                {
                    $searchCount = $this->params["numberOfRows"];
                }
            }
        }

        return $searchCount;
    }

    public function getStartRecord()
    {
        $startRecord = 1;

        if($this->params)
        {
            if(isset ($this->params["startRow"]))
            {
                if(is_array($this->params["startRow"]) && count($this->params["startRow"]) > 0)
                {
                    $startRecord = $this->params["startRow"][0];
                }
                else
                {
                    $startRecord = $this->params["startRow"];
                }
            }
        }

        return $startRecord;
    }

    public function getQueryStringValues($query_string)
    {
        $query  = explode('&', $query_string);
        $params = array();

        foreach( $query as $param )
        {
            list($name, $value) = explode('=', $param);
            $params[urldecode($name)][] = urldecode($value);
        }

        return $params;
    }

    public function checkCredentials($username, $password, $host)
    {
        $id_pwd = $username . ":" . $password;

        $verify_data = $this->service->VerifyCredentials($host, $id_pwd);

        if($verify_data != -1)
        {
            return 1;
        }

        return 0;
    }

    public function setProperties($user_id, $password, $host, $contacts_list)
    {
        if (file_exists("includes/custom"))
        {
            $filePath="includes/custom/";
        }
        else if (file_exists("../includes/custom"))
        {
            $filePath="../includes/custom/";
        }

        $fp = fopen($filePath."login.properties", "w") or die ("Could not open ".$filePath."login.properties file");

        fwrite($fp, "Host=" . $host);
        fwrite($fp, "\nUsername=" . $user_id);
        fwrite($fp, "\nPassword=" . $password);
        fwrite($fp, "\nContactsList=" . $contacts_list);

        fclose($fp);
    }

    private function loadProperties()
    {
        if (file_exists("includes/custom"))
        {
            $filePath="includes/custom/";
        }
        else if (file_exists("../includes/custom"))
        {
            $filePath="../includes/custom/";
        }

        $fp = fopen($filePath."login.properties", "r") or die ("Could not open ".$filePath."login.properties file");

        // iterate through all the lines
	while ($line = fgets($fp))
	{
            // getting the value of the property
            $valueIndex = stripos($line, "=");
            $value = substr($line, $valueIndex +1);


            if (strpos($line, "Host") !== false)
            {
                // if the current line contains 'email' then this value is for 'email'
		$this->host = trim($value);
            }
            elseif (strpos($line, "Username") !== false)
            {
                // if the current line contains 'password' then this value is for 'password'
		$this->uid = trim($value);
            }
            elseif (stripos($line, "Password") !== false)
            {
                // if the current line contains 'account' then this value is for 'account'
		$this->pwd = trim($value);
            }
            elseif (stripos($line, "ContactsList") !== false)
            {
                // if the current line contains 'account' then this value is for 'account'
		$this->contacts_list = trim($value);
            }
       	}

	fclose($fp);
    }
}
?>
